<?php

declare(strict_types=1);

namespace App\Amqp\Consumer;

use App\Event\UserChatEvent;
use App\Helpers\ImUtil;
use App\Helpers\RedisUtil;
use App\Model\Setting\SettingOfficialChat;
use App\Model\User;
use App\Model\UserChat;
use Hyperf\Amqp\Message\Type;
use Hyperf\Amqp\Result;
use Hyperf\Amqp\Annotation\Consumer;
use Hyperf\Amqp\Message\ConsumerMessage;
use PhpAmqpLib\Message\AMQPMessage;
use Psr\EventDispatcher\EventDispatcherInterface;

/**
 * @Consumer(exchange="processImCallback", routingKey="processImCallback", queue="processImCallback.send", name ="ProcessImCallbackConsumer", nums=3)
 */
class ProcessImCallbackConsumer extends ConsumerMessage
{
    /**
     * @var string
     */
    protected $type = Type::DIRECT;

    public $callbackInfo = [];
    public function consumeMessage($data, AMQPMessage $message): string
    {
        $this->callbackInfo = $data;

        $fromImAccount = $this->callbackInfo['fromUserId'];
        $toImAccount   = $this->callbackInfo['toUserId'];
        $userIds       = User::getUserIdByIm([$fromImAccount, $toImAccount]);
        $userId        = $userIds[$fromImAccount];
        $chatUserId    = $userIds[$toImAccount];

        if (strlen($toImAccount) < 15 || strlen($fromImAccount) < 15) {
            log_info(__CLASS__ . "==Error==From:{$fromImAccount}==To:{$toImAccount}");

            return Result::ACK;
        }

        log_info(__CLASS__ . "==From:{$fromImAccount}==To:{$toImAccount}");

        //聊天数量更新
        $userChat = UserChat::updateMsgNum($userId, $chatUserId, 1);

        //小助手消息回复
        $content = $this->callbackInfo['content']['content'] ?? '';
        $this->officialFeedBack($fromImAccount, $toImAccount, $content, $userId);

        //每日任务检测
        make(EventDispatcherInterface::class)->dispatch(new UserChatEvent($userId, $chatUserId, $userChat));

        return Result::ACK;
    }


    /**
     * 小助手消息回复
     */
    function officialFeedBack($fromImAccount = '', $toImAccount = '', $content = '', $fromUserId = 0)
    {
        if (!$content) {
            return false;
        }

        $officialAccount  = env('IM_ACCOUNT_KEFU', '');
        $officialAccount2 = env('IM_ACCOUNT_KEFU2', '');

        if (!in_array($toImAccount, [$officialAccount, $officialAccount2])) return false;

        $key      = "Official_feedback_{$fromImAccount}";
        $lockTime = check_dev_env() ? 30 : env('OFFICIAL_CHAT_OFF_TIME', 3600);

        if ($answer = SettingOfficialChat::getAnswerByKey($content)) {
            return ImUtil::sendTextMsg($fromImAccount, $answer, $officialAccount);
        } else {
            if (RedisUtil::concurrentLock($key, $lockTime)) return false;
        }

        switch ($toImAccount) {
            case $officialAccount2:
                $msg = '你好，我是客服，很高兴为你服务，请你描述想要咨询的相关问题。';
                break;
            case $officialAccount:
                $msg = '你好，我是小助手，很高兴为你服务，请你描述想要咨询的相关问题。';
                break;
        }

        ImUtil::sendInfoTipMsg($fromImAccount, $msg, $toImAccount);

        return true;
    }
}
